package org.openinsula.arena.aws.sqs;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

import com.xerox.amazonws.sqs2.Message;
import com.xerox.amazonws.sqs2.MessageQueue;
import com.xerox.amazonws.sqs2.SQSException;
import com.xerox.amazonws.sqs2.SQSUtils;

public class DefaultSqsManager implements SqsManager, InitializingBean {

	private Logger logger = LoggerFactory.getLogger(getClass());

	private String accessKey;

	private String secretAccessKey;

	@Override
	public void afterPropertiesSet() throws Exception {
		Assert.notNull(accessKey, "'accessKey' must not be null.");
		Assert.notNull(secretAccessKey, "'secretAccessKey' must not be null.");
	}

	public String put(String queueName, String message) throws SQSException {
		logger.info(String.format("Putting '%s' on queue '%s'", message, queueName));

		MessageQueue queue = SQSUtils.connectToQueue(queueName, accessKey, secretAccessKey);
		return queue.sendMessage(message);
	}

	public Message get(String queueName) throws SQSException {
		MessageQueue queue = SQSUtils.connectToQueue(queueName, accessKey, secretAccessKey);
		Message message = queue.receiveMessage();

		if (message != null) {
			logger.info(String.format("Getting message with payload '%s' from queue '%s'", message.getMessageBody(),
					queueName));
		}

		return message;
	}

	@Override
	public void delete(String queueName, Message message) throws SQSException {
		MessageQueue queue = SQSUtils.connectToQueue(queueName, accessKey, secretAccessKey);
		queue.deleteMessage(message);
	}

	public void setAccessKey(String accessKey) {
		this.accessKey = accessKey;
	}

	public void setSecretAccessKey(String secretAccessKey) {
		this.secretAccessKey = secretAccessKey;
	}

}
